"use client";

import React, { useState, useEffect } from "react";
import { XLayerTokenList } from "@/components/XLayerTokenList";
import { CreateXLayerTokenForm } from "@/components/CreateXLayerTokenForm";
import { XLayerTokenDetailModal } from "@/components/XLayerTokenDetailModal";
import { PixelHeader } from "@/components/PixelHeader";
import { useXLayerWebSocket } from "@/hooks/useXLayerWebSocket";
import type { XLayerToken, XLayerStats } from "@/types/xlayer";
import apiClient from "@/lib/api";
import { ChatRoom } from "../components/ChatRoom";

interface Stats {
  totalTokens: number;
  totalVolume: number;
  activeTraders: number;
}

export default function HomePage() {
  const [activeTab, setActiveTab] = useState<"list" | "create">("list");
  const [selectedToken, setSelectedToken] = useState<XLayerToken | null>(null);
  const [tokens, setTokens] = useState<XLayerToken[]>([]);
  const [stats, setStats] = useState<Stats>({
    totalTokens: 0,
    totalVolume: 0,
    activeTraders: 0,
  });
  const [chatOpen, setChatOpen] = useState(false);

  const { isConnected } = useXLayerWebSocket({
    onTokenUpdate: (token: Partial<XLayerToken> & { id: string }) => {
      setTokens((prev: XLayerToken[]) =>
        prev.map((t) => (t.id === token.id ? { ...t, ...token } : t))
      );
      // Also update selectedToken if it's the same one
      if (selectedToken && selectedToken.id === token.id) {
        setSelectedToken(prev => prev ? { ...prev, ...token } : null);
      }
    },
    onNewToken: (token: XLayerToken) => {
      setTokens((prev: XLayerToken[]) => [token, ...prev]);
    },
    onStatsUpdate: (newStats: XLayerStats) => {
      setStats({
        totalTokens: newStats.totalTokens,
        totalVolume: parseFloat(newStats.totalVolume),
        activeTraders: newStats.activeTraders,
      });
    },
  });

  const handleTokenUpdate = (updatedToken: XLayerToken) => {
    // Update the token in the list
    setTokens((prev: XLayerToken[]) =>
      prev.map((t) => (t.id === updatedToken.id ? updatedToken : t))
    );
    // Update the selected token if it's the same one
    if (selectedToken && selectedToken.id === updatedToken.id) {
      setSelectedToken(updatedToken);
    }
  };

  // 加载初始数据
  useEffect(() => {
    const loadData = async () => {
      try {
        // 并行加载统计和代币
        const [statsData, tokensData] = await Promise.all([
          apiClient.getXLayerStats(),
          apiClient.getXLayerTokens(),
        ]);

        setStats({
          totalTokens: statsData.totalTokens,
          totalVolume: parseFloat(statsData.totalVolume),
          activeTraders: statsData.activeTraders,
        });
        setTokens(tokensData.tokens);
      } catch (error) {
        console.error("Failed to load data:", error);
      }
    };

    loadData();
  }, []);

  const loadTokens = async () => {
    try {
      const tokensData = await apiClient.getXLayerTokens();
      setTokens(tokensData.tokens);
    } catch (error) {
      console.error("Failed to load tokens:", error);
    }
  };

  const handleTokenCreated = (newToken: XLayerToken) => {
    setTokens((prev: XLayerToken[]) => [newToken, ...prev]);
    setActiveTab("list");
  };

  return (
    <div className="min-h-screen" style={{ background: "var(--background)" }}>
      <PixelHeader />
                 

      {/* 主内容 */}
      <main className="app-container py-8">
        {/* 标题和统计 */}
        <div className="text-center mb-12 w-full">
          <h1 className="text-4xl md:text-6xl font-bold text-white mb-4">
            X Layer Launch Pad
          </h1>
          <p
            className="text-lg md:text-xl mb-8"
            style={{ color: "var(--foreground)" }}
          >
            Create and trade tokens on X Layer - Supports bonding curve pricing
          </p>

          {/* 统计数据 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div className="pixel-card p-6 text-center">
              <div className="text-3xl font-bold text-orange-400 mb-2">
                {stats.totalTokens}
              </div>
              <div className="text-gray-400">Total number of tokens</div>
            </div>
            <div className="pixel-card p-6 text-center">
              <div className="text-3xl font-bold text-orange-400 mb-2">
                {stats.totalVolume} OKB
              </div>
              <div className="text-gray-400">Total trading volume</div>
            </div>
            <div className="pixel-card p-6 text-center">
              <div className="text-3xl font-bold text-orange-400 mb-2">
                {stats.activeTraders}
              </div>
              <div className="text-gray-400">Active Traders</div>
            </div>
          </div>

          {/* WebSocket Status */}
          <div className="mb-8 flex justify-center gap-4">
            <div
              className={`inline-flex items-center px-3 py-1 rounded text-sm ${
                isConnected
                  ? "bg-green-500/20 text-green-400"
                  : "bg-red-500/20 text-red-400"
              }`}
            >
              <div
                className={`w-2 h-2 rounded-full mr-2 ${
                  isConnected ? "bg-green-400" : "bg-red-400"
                }`}
              />
              {isConnected ? "connected" : "disconnected"}
            </div>
            {/* Chat Toggle Button */}
            <button
              onClick={() => setChatOpen(!chatOpen)}
              className={`px-4 py-2 rounded text-sm font-medium transition-colors ${
                chatOpen
                  ? "bg-purple-600 text-white hover:bg-purple-700"
                  : "bg-gray-600 text-white hover:bg-gray-700"
              }`}
            >
              {chatOpen ? "close chat room" : "open chat room"}
            </button>
          </div>
        </div>

        {/* Navigation Tabs */}
        <div className="flex justify-center mb-8">
          <div className="flex gap-2">
            <button
              onClick={() => setActiveTab("list")}
              className={`pixel-btn ${activeTab === "list" ? "active" : ""}`}
            >
              token list ({tokens.length})
            </button>
            <button
              onClick={() => setActiveTab("create")}
              className={`pixel-btn ${activeTab === "create" ? "active" : ""}`}
            >
              create token
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="pixel-card p-6">

          {activeTab === "list" ? (
            <XLayerTokenList
              tokens={tokens}
              onTokenSelect={setSelectedToken}
              onRefresh={loadTokens}
            />
          ) : (
            <CreateXLayerTokenForm onTokenCreated={handleTokenCreated} />
          )}
        </div>
      </main>
    <ChatRoom isOpen={chatOpen} onToggle={() => setChatOpen(!chatOpen)} />
      {/* Token Detail Modal */}
      {selectedToken && (
        <XLayerTokenDetailModal
          token={selectedToken}
          isOpen={!!selectedToken}
          onClose={() => setSelectedToken(null)}
          onTokenUpdate={handleTokenUpdate}
        />
      )}
    </div>
  );
}
